package com.fyt.ZhongYaoApp.service.impl;

import com.fyt.ZhongYaoApp.exeception.AddressBookBusinessException;
import com.fyt.ZhongYaoApp.exeception.ShoppingCartBusinessException;
import com.fyt.ZhongYaoApp.mapper.AddressBookMapper;
import com.fyt.ZhongYaoApp.mapper.OrderDetailMapper;
import com.fyt.ZhongYaoApp.mapper.OrderMapper;
import com.fyt.ZhongYaoApp.mapper.ShoppingCarMapper;
import com.fyt.ZhongYaoApp.pojo.*;
import com.fyt.ZhongYaoApp.pojo.dto.OrdersDTO;
import com.fyt.ZhongYaoApp.pojo.dto.OrdersSubmitDTO;
import com.fyt.ZhongYaoApp.pojo.vo.OrderSubmitVO;
import com.fyt.ZhongYaoApp.service.OrderService;
import com.fyt.ZhongYaoApp.service.UserService;
import com.fyt.ZhongYaoApp.utils.MessageUtil;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBook;

    @Autowired
    private ShoppingCarMapper shoppingCarMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserService userService;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        // 判断订单是否合法（地址簿为空，购物车为空）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            // 抛出业务异常
            throw new AddressBookBusinessException(MessageUtil.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCar shoppingCar = new ShoppingCar();

        // 获取用户id
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        shoppingCar.setUserId(userId);


        List<ShoppingCar> shoppingCarList = shoppingCarMapper.list(shoppingCar);
        // 查询当前购物车是否为空
        if (shoppingCarList == null || shoppingCarList.size() == 0) {
            // 如果购物车为空，抛出异常
            throw new ShoppingCartBusinessException(MessageUtil.SHOPPING_CART_IS_NULL);
        }

        // 向订单插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        System.out.println("order复制前的值" + orders);

        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(orders.UN_PAID);// 设置为未付款
        orders.setStatus(Orders.PENDING_PAYMENT);// 设置为待支付状态
        orders.setNumber(String.valueOf(System.currentTimeMillis()));// 使用系统时间戳创建订单号
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setUserId((long)userId);
        orders.setUserName(username);
        double total = 0;
        for (ShoppingCar shoppingCar1 : shoppingCarList) {
            total += shoppingCar1.getAmount();
        }
        orders.setAmount(BigDecimal.valueOf(total));
        System.out.println("order复制后的值" + orders);
        // 插入订单信息
        orderMapper.insert(orders);

        /*
        订单明细
         */
        List<OrderDetail> orderDetailList = new ArrayList();
        // 向订单明细表插入n条数据
        for (ShoppingCar car : shoppingCarList) {
            OrderDetail orderDetail = new OrderDetail();// 订单明细
            BeanUtils.copyProperties(car, orderDetail);
            orderDetail.setOrderId(orders.getId());// 设置订单明细关联的订单id
            orderDetailList.add(orderDetail);
            System.out.println("订单明细：" + orderDetail);

        }
        System.out.println("订单明细列表" + orderDetailList);
        orderDetailMapper.insertBatch(orderDetailList);

        // 清空当前用户购物车数据
        shoppingCarMapper.deleteById(userId);

        // 封装VO返回结束
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 查看订单详情
     * @param ordersDTO
     * @return
     */
    @Override
    public List<OrderDetail> showDetail(OrdersDTO ordersDTO) {


        return orderDetailMapper.showDetailByOrderId(ordersDTO.getId());
    }

    @Override
    public List<Orders> orderList() {

        // 封装订单信息
        Orders orders = new Orders();

        // 封装用户信息
        Integer userId;
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User user = userService.findByUserName(username);
        userId = user.getId();
        orders.setUserId(userId.longValue());
        return orderMapper.orderList(orders);
    }
}
